<?php

namespace IDock\Insurance\ACIC\Response;


use IDock\Http\Response;
use SimpleXMLElement;

class AllACICResponse extends Response
{

    public function resolve(): Response
    {
        $body = $this->getBody();

        if ($body) {
            libxml_disable_entity_loader(false);
            $body = simplexml_load_string($body);

            $body = $this->objectToArray($body);

            $errorCode = $body['Head']['ErrorCode'] ?? '';

            if ($errorCode !== '0000') {
                if ($error = $this->errorTrans($body['Head']['ErrorMessage'] ?? '未知错误')) {
                    $this->setError($error);
                } else {
                    $this->setError($body['Head']['ErrorMessage'] ?? '未知错误');

                }
                return  $this;
            }

            $this->setBody($body['Body'] ?? '');
        }

        return $this;
    }

    protected function objectToArray($object) {
        if( count($object)==0 )  return trim((string)$object);
        $result = array();
        $object = is_object($object) ? get_object_vars($object) : $object;
        foreach ($object as $key => $val) {
            $val = (is_object($val) || is_array($val)) ? $this->objectToArray($val) : $val;
            $result[$key] = $val;
        }
        return $result;
    }

    protected function errorTrans($error)
    {

    }
}
